package team.knowers.qzhserver.user.userData.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.knowers.qzhserver.common.api.CommonResult;
import team.knowers.qzhserver.user.user.entity.dao.UserDO;
import team.knowers.qzhserver.user.user.service.impl.UserServiceImpl;
import team.knowers.qzhserver.user.userData.entity.vo.UserDataDetailsVO;
import team.knowers.qzhserver.user.userData.service.impl.UserDataServiceImpl;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;

/**
 * 用户数据控制层
 *
 * @author xtg
 * @date 2024/2/15 18:27
 */
@Controller
@RequestMapping("/userData")
@Tag(name = "UserDataController", description = "用户数据操作")
public class UserDataController {
    @Autowired
    private UserDataServiceImpl userDataService;
    @Autowired
    private UserServiceImpl userService;

    @Operation(summary = "获取个人信息数据",description = "会判断点击者是否为此页面用户")
    @GetMapping("/{id}")
    @ResponseBody
    public CommonResult getUserData(@PathVariable String id, Principal principal) {
        //防止参数不合理
        if(userService.userStatus(id)==-1)
            return CommonResult.failed("用户id不存在");
        UserDataDetailsVO userVO = userDataService.getUserData(id);
        if (userVO != null) {
            String username = (String) userDataService.getUserOnline(principal).get("username");
            if (username.equals(userVO.getUsername()))
                userVO.setIsSamePerson(true);
            else
                userVO.setIsSamePerson(false);
            return CommonResult.success(userVO);
        } else
            return CommonResult.failed("获取失败");
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/info")
    @ResponseBody
    public CommonResult getUserOnline(Principal principal) throws Exception {
        if (principal == null) {
            return CommonResult.unauthorized(null);
        }
        String username = principal.getName();
        UserDO user = userService.getUserByUsername(username);
        Map<String, Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        return CommonResult.success(data);
    }


}
